#!/usr/bin/env python3

from switchyard.lib.address import *
from switchyard.lib.packet import *
from switchyard.lib.userlib import *
from threading import *
import time

def switchy_main(net):
    my_interfaces = net.interfaces()
    mymacs = [intf.ethaddr for intf in my_interfaces]

    filename = "lab_6/blastee_params.txt"
    with open(filename) as f:
        content = f.readlines()
    params = content[0].split()
    blaster_ip = params[1]
    num_pkt = int(params[3])

    while True:
        gotpkt = True
        try:
            timestamp,dev,pkt = net.recv_packet()
            log_debug("Device is {}".format(dev))
        except NoPackets:
            log_debug("No packets available in recv_packet")
            gotpkt = False
        except Shutdown:
            log_debug("Got shutdown signal")
            break

        if gotpkt:
            log_debug("I got a packet from {}".format(dev))
            log_debug("Pkt: {}".format(pkt))

            ack_pkt = Ethernet() + IPv4() + UDP()
            ack_pkt[0].src = pkt[0].dst
            ack_pkt[0].dst = pkt[0].src
            ack_pkt[1].src = pkt[1].dst
            ack_pkt[1].dst = IPv4Address(blaster_ip)
            ack_pkt[1].protocol = IPProtocol.UDP

            seq_num = pkt[3].data[:4]
            ack_pkt.add_header(seq_num)

            
            bytes_data = pkt[3].to_bytes()
            payload_bytes = bytes_data[6:]
            ack_pkt.add_header(payload_bytes[:8])
            log_info("payload: {}".format(payload_bytes))
            zero = b'x\00x\00x\00x\00' # 用0补齐
            if len(payload_bytes[:8]) < 8:
                ack_pkt.add_header(zero[:8-len(payload_bytes[:8])]) 

            net.send_packet("blastee-eth0", ack_pkt)

    net.shutdown()
